<template>
  <el-container>
    <el-header class="height_auto">
      <!--<form-panel-->
        <!--:formid="searchfromid"-->
        <!--v-show="searchfromid != null"-->
        <!--ref="searchfrom"-->
        <!--class="grid_top_btn_box"-->
      <!--&gt;-->
        <!--<template slot="cfg_buttonArray">-->
          <!--<vxe-button size="mini" content="搜索" @click="search"></vxe-button>-->
        <!--</template>-->
      <!--</form-panel>-->
    </el-header>
    <el-main>
      <div class="bk_gridtable">
        <vxe-grid
          :id="settings.id"
          :ref="xGrid"
          :resizable="settings.resizable"
          :border="settings.border"
          :loading="loading"
          :export-config="settings.exportConfig"
          :data="tableData"
          :align="settings.allAlign"
          :columns="settings.tableColumn"
          :height="settings.height"
          :max-height="settings.maxHeight"
          :auto-resize="settings.autoResize"
          :sync-resize="settings.syncResize"
          :stripe="settings.stripe"
          :round="settings.round"
          :size="settings.size"
          :header-align="settings.headerAlign"
          :footer-align="settings.footerAlign"
          :show-header="settings.showHeader"
          :highlight-current-row="settings.highlightCurrentRow"
          :highlight-hover-row="settings.highlightHoverRow"
          :highlight-current-column="settings.highlightCurrentColumn"
          :highlight-hover-column="settings.highlightHoverColumn"
          :highlight-cell="settings.highlightCell"
          :row-class-name="settings.rowClassName"
          :cell-class-name="settings.cellClassName"
          :header-row-class-name="settings.headerRowClassName"
          :header-cell-class-name="settings.headerCellClassName"
          :footer-row-class-name="settings.footerRowClassName"
          :footer-cell-class-name="settings.footerCellClassName"
          :cell-style="settings.cellStyle"
          :header-cell-style="settings.headerCellStyle"
          :footer-cell-style="settings.footerCellStyle"
          :row-style="settings.rowStyle"
          :header-row-style="settings.headerRowStyle"
          :footer-row-style="settings.footerRowStyle"
          :show-footer="settings.showFooter"
          :footer-method="settings.footerMethod"
          :merge-cells="settings.mergeCells"
          :merge-footer-items="settings.mergeFooterItems"
          :span-method="settings.spanMethod"
          :footer-span-method="settings.footerSpanMethod"
          :show-overflow="settings.showOverflow"
          :show-header-overflow="settings.showHeaderOverflow"
          :show-footer-overflow="settings.showFooterOverflow"
          :column-key="settings.columnKey"
          :row-key="settings.rowKey"
          :keep-source="settings.keepSource"
          :z-index="settings.zIndex"
          :column-config="settings.columnConfig"
          :seq-config="settings.seqConfig"
          :sort-config="settings.sortConfig"
          :filter-config="settings.filterConfig"
          :import-config="settings.importConfig"
          :print-config="settings.printConfig"
          :radio-config="settings.radioConfig"
          :checkbox-config="settings.checkboxConfig"
          :tooltip-config="settings.tooltipConfig"
          :tree-config="settings.treeConfig"
          :context-menu="settings.contextMenu"
          :keyboard-config="settings.keyboardConfig"
          :edit-config="settings.editConfig"
          :valid-config="settings.validConfig"
          :edit-rules="settings.editRules"
          :empty-render="settings.emptyRender"
          :custom-config="settings.customConfig"
          :animat="settings.animat"
          :cloak="settings.cloak"
          :delay-hover="settings.delayHover"
          :scroll-x="settings.scrollX"
          :scroll-y="settings.scrollY"
          :params="settings.params"
          :form-config="settings.formConfig"
          :pager-config="settings.pagerConfig"
          :proxy-config="settings.proxyConfig"
          :zoom-config="settings.zoomConfig"
          @toolbar-button-click="toolbarButtonClickEvent"
          @checkbox-change="checkboxChange"
          @cell-dblclick="dblclick"
        >
          <vxe-toolbar v-show='settings.tableToolbar' slot="toolbar"
          :custom="settings.tableToolbar && settings.tableToolbar.custom"
          :zoom="settings.tableToolbar &&settings.tableToolbar.zoom"
          :refresh="settings.tableToolbar &&settings.tableToolbar.refresh"
          :print="settings.tableToolbar &&settings.tableToolbar.print"
          :export="settings.tableToolbar &&settings.tableToolbar.export"
          >
          <!--工具条开始-->
          <template  v-for="(item,index) in settings.tableToolbar?settings.tableToolbar.buttons:[]" >
             <span v-if='item.isSlot'  slot="buttons"  :key='index' class="vxe-button"><slot  :name='item.name'/></span>
            <vxe-button v-else slot='buttons'
            :key= "index"
            :icon="item.icon"
            :name='item.name'
            @click='item.handler'
            >{{item.name}}
            <template v-show='item.dropdowns' slot='dropdowns' v-for='(dropbtn,i2) in item.dropdowns'>
              <vxe-button :type='dropbtn.type' :disabled="dropbtn.disabled"
            :key= "i2"
            :name='dropbtn.name'
            @click='dropbtn.handler'>{{dropbtn.name}}</vxe-button>
            </template>
            </vxe-button>
          </template>
          <template  v-for="(item,index) in settings.tableToolbar?settings.tableToolbar.tools:[]" >
            <span v-if='item.isSlot'  slot="tools"  :key='index' class="bk_tools"><slot  :name='item.name'/></span>
            <vxe-button v-else :key='index' slot="tools" @click="item.handler" >
              {{item.name}}
              <template v-show='item.dropdowns' slot='dropdowns' v-for='(dropbtn,i2) in item.dropdowns'>
              <vxe-button :type='dropbtn.type' :disabled="dropbtn.disabled"
            :key= "i2"
            @click='dropbtn.handler'>{{dropbtn.name}}</vxe-button>
            </template>
            </vxe-button>
          </template>
          </vxe-toolbar>
           <!--工具条结束-->
          <template v-slot:operate="{ row }">
            <slot name="tableButton" :row="row"> </slot>
            
          </template>
        </vxe-grid>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import formPanel from "@/components/formpanel";
import SnowflakeId from "snowflake-id";
import Sortable from 'sortablejs'
import "font-awesome/css/font-awesome.min.css";
import XEUtils from "xe-utils";
import request from "@/utils/requestutil";

export default {
  name: "GirdPage",
  props: {
    config: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  components: {
    formPanel
  },
  data() {
    return {
      // searchfromid: null,
      xGrid: "grid_" + this.guid(),
      refreshpage: false,
      options: {
        treeConfigKey: "",
        checkType: "radio", //check // no
        isEdit: false, //是否行内编辑
        isIndex: false, //是否有索引
        isSort: false, //是否拖拽排
        isRemotePage: false,
        tableToolbar: {},
        shieldBtn: false,
        useDefaultButtons:false,
      },
      // 属性配置
      settings: {
        templateCfgUrl: "gridColumncfg",
        dataUrl: "gridDataUrl",
        datatemplet: null,
        hasFixed:true,
        sortable:false,
        flag: null,
        id: this.guid(),
        resizable: true, // 所有列是否允许拖动列宽调整大小
        hideToolBar:false,
        tableToolbar: {
          export: false,
          custom: true,
          tools:[],
          buttons: [
            { code: "insert_actived", name: "新增", icon: "fa fa-plus" },
            { code: "delete", name: "直接删除", icon: "fa fa-trash-o" },
            { code: "mark_cancel", name: "删除/取消", icon: "fa fa-trash-o" },
            {
              code: "save",
              name: "保存",
              icon: "fa fa-save",
              status: "success"
            }
          ],
          refresh: true,
          import: false,
          print: false,
          zoom: true
        },
        tableColumn: [],
        exportConfig: {
          type: "xlsx",
          types: ["xlsx", "csv", "html", "xml", "txt"],
          modes: ["current", "all"],
          remote: true,
          exportMethod: this.remoteExportMethod
        }, // 导出配置项
        allAlign: "left", // //所有的列对齐方式String left（左对齐）, center（居中对齐）, right（右对齐）
        height: 1000,
        maxHeight: 1000,
        autoResize: false, // 是否自动监听父容器变化去更新响应式表格宽高
        syncResize: false, // 是否自动根据状态属性去更新响应式表格宽高
        stripe: true, // 是否带有斑马纹
        round: true, // 是否圆角边框
        size: "mini", // 表格的尺寸
        loading: "loading", // 表格是否显示加载中boolean
        // 是否带有边框
        border: true,
        // 所有的表头列的对齐方式 left（左对齐）, center（居中对齐）, right（右对齐）
        headerAlign: "left",
        // 所有的表尾列的对齐方式
        footerAlign: "left",
        // 是否显示表头
        showHeader: true,
        // 是否要高亮当前选中行
        highlightCurrentRow: true,
        // 鼠标移到行是否要高亮显示
        highlightHoverRow: true,
        // 是否要高亮当前选中列
        highlightCurrentColumn: false,
        // 鼠标移到列是否要高亮显示
        highlightHoverColumn: false,
        // 激活单元格编辑时是否高亮显示
        highlightCell: false,
        // 是否显示表尾合计
        showFooter: false,
        // 表尾合计的计算方法
        footerMethod: this.footerMethodExtends,
        // 给行附加 className
        rowClassName: "",
        // 给单元格附加 className
        cellClassName: "",
        // 给表头的行附加 className
        headerRowClassName: "",
        // 给表头的单元格附加 className
        headerCellClassName: "",
        // 给表尾的行附加 className
        footerRowClassName: "",
        // 给表尾的单元格附加 className
        footerCellClassName: "",
        // 给单元格附加样式
        cellStyle: {},
        // 给表头单元格附加样式
        headerCellStyle: {},
        // 给表尾单元格附加样式
        footerCellStyle: {},
        // 给行附加样式
        rowStyle: {},
        // 给表头行附加样式
        headerRowStyle: {},
        // 给表尾行附加样式
        footerRowStyle: {},
        // 合并行或列
        spanMethod: this.spanMethodExtends,
        // 表尾合并行或列
        footerSpanMethod: this.footerSpanMethodExtends,
        // 设置所有内容过长时显示为省略号  ellipsis（只显示省略号）,title（并且显示为原生 title）,tooltip（并且显示为 tooltip 提示）
        showOverflow: "title",
        // 设置表头所有内容过长时显示为省略号
        showHeaderOverflow: "title",
        // 设置表尾所有内容过长时显示为省略号
        showFooterOverflow: "title",
        // 所有列宽度
        columnWidth: "20%",
        // 所有列最小宽度，把剩余宽度按比例分配
        columnMinWidth: "20%",
        // 主键配置
        columnKey: false,
        rowKey: false,
        zIndex: 999,
        keepSource: false,
        // 序号配置项
        seqConfig: {
          startIndex: 100
        },
        // 排序配置项
        sortConfig: {
          trigger: "cell", // 所有列是否使用服务端排序，如果设置为 true 则不会对数据进行处理
          remote: true
        },
        // 筛选配置项
        filterConfig: {
          remote: true // 删选为远程删选
        },
        // 单选框配置
        radioConfig: {
          // labelField: 'id', // 单选框显示的字段名，可以直接显示在单选框中
          reserve: true, // 是否保留勾选状态，对于某些场景下非常有用，比如数据被刷新之后还保留之前选中的状态（需要有 row-id）
          highlight: true
        },
        // 复选框配置项
        checkboxConfig: {
          // labelField: 'id', //
          reserve: true, //
          highlight: true, //
          range: true //
        },
        // tooltip 配置项
        tooltipConfig: {
          enabled: true,
          theme: "light", // dark
          enterable: true,
          leaveDelay: 500,
          contentMethod: this.contentMethodExtends
        },
        // 导入配置项
        importConfig: {
          remote: true,
          importMethod: this.importMethodExtends,
          types: ["xlsx", "csv", "txt"], // ['csv', 'html', 'xml', 'txt']
          modes: ["insert"] // covering 覆盖,insert 插入
        },
        // 打印配置项
        printConfig: {
          sheetName: "文档页",
          mode: "current", // 输出数据的方式 ,current
          modes: ["current", "selected", "all"]
        },
        // 树形结构配置项
        treeConfig: false,
        // 快捷菜单配置项
        contextMenu: false,
        // 按键配置项
        keyboardConfig: {
          isArrow: true, // 开启方向键
          isDel: true // 删除按钮
        },
        // 单击编辑,单元格
        editConfig: {
          // trigger: "click",
          // mode: "row",
          showStatus: true,
          activeMethod: this.activeCellMethod,
          showIcon: false, //取消表头图标
          showAsterisk: false //*取消
        },
        // 校验配置项
        validConfig: {}, // 后面在补充
        // 校验规则配置项
        editRules: {}, // 后面在补充
        // 自定义列配置项
        customConfig: {
          mainObject: this,
          storage: true,
          checkMethod: this.checkColumnMethodExtends
        },
        // 横向虚拟滚动配置项（注：当 tree-config 启用后纵向虚拟滚动将无效）
        scrollX: {
          gt: 60, // 指定大于指定行时自动启动纵向虚拟滚动，如果为 0 则总是启用，如果为 -1 则关闭（注：启用纵向虚拟滚动之后将不能支持动态行高）
          oSize: 0 // 指定每次渲染的数据偏移量，偏移量越大渲染次数就越少，但每次渲染耗时就越久（对于古董级的低性能浏览器可以设置大一点）
        },
        // 纵向虚拟滚动配置（注：当 tree-config 启用后纵向虚拟滚动将无效）
        scrollY: {
          gt: 100, // 指定大于指定行时自动启动纵向虚拟滚动，如果为 0 则总是启用，如果为 -1 则关闭（注：启用纵向虚拟滚动之后将不能支持动态行高）
          oSize: 0 // 指定每次渲染的数据偏移量，偏移量越大渲染次数就越少，但每次渲染耗时就越久（对于古董级的低性能浏览器可以设置大一点）
        },
        // 优化相关
        cloak: false,
        animat: true,
        delayHover: 250, // 当表格发生拖动、滚动...等行为时，至少多少毫秒之后才允许触发 hover 事件
        // 额外的参数
        params: {},
        queryParam: {},
        formConfig: {
          items: []
        },
        pagerConfig: {
          pageSize: 40,
          total: undefined,
          pagerCount: 7,
          pageSizes: [10, 20, 40, 50, 100],
          align: undefined
        },
        proxyConfig: {
          autoLoad: false,
          seq: true, // 启用动态序号代理
          sort: true, // 启用排序代理
          filter: true, // 启用筛选代理
          form: false, // 开启form表单模式
          ajax: {
            query: ({ $grid, page, sort, filters, form, params }) => {
              let settings = this.settings;
              let $t = this;
              let main = $grid.customConfig.mainObject;
              // 处理排序条件
              let searchdata = main.getSearchData();

              const queryParams = Object.assign(
                {
                  orderField: sort.property,
                  order: sort.order,
                  page: page.currentPage,
                  pageRows: page.pageSize,
                  isInit: page.currentPage == 1 || main.refreshpage
                },
                this.tableForm,
                settings.params,
                main.queryParam
              );

              let voParam = { ...searchdata };
              voParam=Object.assign(
                voParam,
                this.tableForm,
                settings.params
              );
              // var promise =  XEAjax.get(`https://api.xuliangzhan.com:10443/api/pub/page/list/${page.pageSize}/${page.currentPage}`, queryParams)
              // console.log(queryParams)
              $t.queryPageInfo = $t.queryPageInfo || {};
              $t.queryPageInfo.currentPage = page.currentPage;
              return new Promise((resolve, reject) => {
                request({
                  url: this.settings.dataUrl,
                  data: { templet: this.settings.datatemplet, ...queryParams },
                  voParam: voParam,
                  method: "post"
                })
                  .then(response => {
                    response = response.obj || response;
                    let page = $t.queryPageInfo;
                    if (response.page) {
                      page = {
                        pageSize: response.page.pageRows,
                        currentPage: response.page.page,
                        total: parseInt(response.page.total)
                      };
                    }
                    main.refreshpage = false;
                    $t.queryPageInfo = page;
                    const temp = {
                      page: page,
                      result: response.data
                    };
                    //   let g=$t.$refs[$t.xGrid]
                    //  // g.loadData(response.data)
                    //  // g.pagerConfig={}
                    //   window.grid=$t.$refs[$t.xGrid]
                    // console.log(temp)
                    resolve(temp);
                  })
                  .catch(response => {
                    reject(response);
                  });
              });
            }
            // delete: ({ body }) => XEAjax.post('https://api.xuliangzhan.com:10443/api/pub/save', body),
            // save: ({ body }) => XEAjax.post('https://api.xuliangzhan.com:10443/api/pub/save', body)
          }
        }
      },
      // 是否显示异步加载
      loading: false,
      tableData: [],
      tableForm: {} // form表单为空
    };
  },
  watch: {
    config: {
      // 对传递过来的数据进行监听, 如果父组件数据发生改动,子组件对应发生变化
      handler(val, oldVal) {
        this.initGriData(val);
      },
      deep: true,
      immediate: true
    }
  },

  created() {
    this.settings;
  },
  mounted() {
    // 初始化表头以及查询项数据
    this.getTableColumn(true);
  },
  methods: {
    getSearchData() {
      // if (this.searchfromid) {
      //   console.log(this.$refs.searchfrom.getData4Search());
      //   return this.$refs.searchfrom.getData4Search();
      // }
      return {};
    },
    // search() {
    //   this.$refs[this.xGrid].commitProxy("query");
    // },
    dicFormater({ cellValue, row, column }) {
      if (_.isEmpty(cellValue)) return "";
      let key = column.own.props.dicFlag;

      let nm = this.$dicManager.getName(key, cellValue);
      return nm;
    },
    initGriData(val) {
      if(this.sortable)this.sortable.destroy();
      val.settings = _.isEmpty(val.settings) ? {} : val.settings;
      // 对options的数据进行封装
      this.initOptions(this, val);
      // 对settings的数据进行封装
      this.initSetting(this, val.settings);
     
    },
    setTableData(data){
      this.tableData=data;
    },
    initSetting(that, settings) {
      _.forEach(settings, function(value, key) {
        that.settings[key] = value;
      });
      
    },
    initRowDrop(){
      this.$nextTick(() => {
        let xTable = this.$refs[this.xGrid];
        this.sortable = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".vxe-body--row",
            onEnd: ({ newIndex, oldIndex }) => {
              let currRow = this.tableData.splice(oldIndex, 1)[0];
              this.tableData.splice(newIndex, 0, currRow);
              this.$emit("afterSort",{g:xTable,newIndex:newIndex,oldIndex:oldIndex})
            },
          }
        );
      });
    },
    initOptions(that, val) {
      if (!_.isEmpty(val.options)) {
        let opt = that.options;
        that.options=_.assign(that.options,val.options);///.isIndex=val.isIndex||false;
        opt.tableToolbar = _.isEmpty(opt.tableToolbar) ? {} : opt.tableToolbar;
        
        let tools=[];
        _.forEach(opt.tableToolbar, function(value, key) {
          if (key === "buttons" && opt.shieldBtn === false) {
            let arr = [];
            if(opt.useDefaultButtons)arr=that.settings.tableToolbar.buttons;
            else that.settings.tableToolbar.buttons=[];
            _.forEach(opt.tableToolbar.buttons, function(value2, key2) {
              const index = _.findIndex(
                that.settings.tableToolbar.buttons,
                data => data.code === value2.code
              );
              if (index === -1) {
                arr.push(value2);
                // console.log(arr)
              } else {
               arr[index] = value2;
              }
            });
            if (!_.isEmpty(arr)) {
              that.settings.tableToolbar.buttons=[];
              _.forEach(arr, function(value, key) {
                // console.log(arr)d
                that.settings.tableToolbar.buttons.push(value);
              });
            }
          } else {
            that.settings.tableToolbar[key] = value;
          }
        });
      }
    },
    getTableColumn(isInit) {
      isInit = true;
      let $t = this;
      
      if(this.settings.flag){
        request({
          url: this.settings.templateCfgUrl,
          data: { flag: this.settings.flag, isInit: isInit },
          method: "post"
        }).then(data => {
          let queryForm = data.queryForm;
          if (!_.isEmpty(queryForm)) {
            // $t.searchfromid = queryForm;
          }

          let objRules = {},fixed=this.settings.hasFixed;
          for (let s in data.tableColumns) {
            let editrules = [];
            let rules = {};
            let itemRender = data.tableColumns[s].editRender || {};
            itemRender.attrs = {};
            if (itemRender && itemRender.props && itemRender.props.dicFlag) {
              data.tableColumns[s].props = itemRender.props;
              data.tableColumns[s].itemRender = undefined;
              data.tableColumns[s].formatter = this.dicFormater;
            }
            if (itemRender && itemRender.props) {
              if (itemRender.props.type == "int") {
                itemRender.attrs.type = "number";
              }
              itemRender.props.type = itemRender.attrs.type;

              data.tableColumns[s].headerAlign = "center";
              data.tableColumns[s].align = data.tableColumns[s].align
                ? data.tableColumns[s].align
                : "center";
            }
              data.tableColumns[s].width = data.tableColumns[s].width>0?(data.tableColumns[s].width+"px"): "120px";
            if(!fixed){
              data.tableColumns[s].fixed=undefined;
            }
          }

          // $t.settings.editRules = objRules;

          $t.settings.datatemplet = data.templet;
          if (data.queryForm) {
          }
          $t.tableColumnsFilter(data.tableColumns, this);
          //if(data.queryItems)
          //$t.tableSearchItemFilter(data.queryItems, this)
          //console.log('grid',$t.$refs[$t.xGrid])
          // window.grid=$t.$refs[$t.xGrid];
          $t.$refs[$t.xGrid].commitProxy("query");
          if (isInit) {
            // 处理分页信息,后端第一次获取请求时才传递分页数据
            // console.log(data)
          }
        });
      }else if(this.settings.tableColumn){
        let cm=this.settings.tableColumn
        for(let i=0;i<cm.length;i++){
          if (cm[i].props && cm[i].props.dicFlag) {
            cm[i].formatter = this.dicFormater;
          }
        }
          this.tableColumnsFilter([], this)
      }
    },
    refreshFirst() {
      this.$refs[this.xGrid].commitProxy("query");
    },
    refresh() {
      this.$refs[this.xGrid].commitProxy("query");
    },
    refresh4All() {
      this.refreshpage = true;
      this.$refs[this.xGrid].commitProxy("query");
    },
    //重载数据
    queryData(queryParams) {
      this.queryParam = queryParams || {};
      this.$refs[this.xGrid].commitProxy("query");
    },
    loadData(queryParam) {
      this.$refs[this.xGrid].commitProxy("query");
    },
    // 表头数据处理器
    tableColumnsFilter: function(val, that) {
      // 默认给每一条数据添加远程数据库排序
      _.forEach(val, data =>{
        data["remoteSort"] = true
        });
      let columns=[];
      if (that.settings.expandCol) {
        columns.push(that.settings.expandCol)
      }
      // for(let i=0;i<this.settings.tableColumn.length;i++){
      //   that.settings.tableColumn[i].fixed='left';
      // }
        that.settings.tableColumn = _.concat(that.settings.tableColumn, val);
     let opt = that.options;
       // that.settings.tableColumn = [];
        let fixed=this.settings.hasFixed?"left":""
        if (opt.isIndex) {
          columns.push({
            type: "seq",
            title: "No.",
            width: 60,
              fixed:fixed,
            align: "center"
          });
        }
        switch (opt.checkType) {
          case "no":
            break;
          case "check":
            columns.push({
              type: "checkbox",
              width: 40,
              align: "center",
                fixed:fixed
            });
            break;
          case "radio":
            columns.push({
              type: "radio",
              width: 40,
              align: "center",
              fixed:fixed
            });
            break;
        }
        if(that.settings.tableColumn&& that.settings.tableColumn.length>0){
          columns.push(...that.settings.tableColumn);
        }
        that.settings.tableColumn=columns;
      // 把远程获取的表头数据到当前
      if (that.settings.operations) {
        that.settings.tableColumn.push({
          field: "operations",
          title: "操作",
          // fixed:"left",
          width: 120,
          // fixed:"right",
          slots: { default: "operate" }
        });
      }
      if(this.settings.sortable){
        this.initRowDrop()
      }
    },
    // 处理搜索项数据
    tableSearchItemFilter: function(val, that) {
      console.log(val);
      // 必须添加$符号才能正常显示
      _.forEach(
        val,
        data => (data.itemRender.name = "$" + data.itemRender.name)
      );
      // 默认添加搜索和重置按钮
      val.push({
        span: 24,
        align: "center",
        collapseNode: false,
        itemRender: {
          name: "$buttons",
          children: [
            {
              props: {
                type: "submit",
                content: "搜索",
                status: "primary"
              }
            },
            {
              props: {
                type: "reset",
                content: "重置"
              }
            }
          ]
        }
      });
      // 设置默认查询项
      that.settings.formConfig.items = val;
      // console.log(val)
    },
    formatDate({ cellValue }) {
      return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
    },
    checkColumnMethodExtends({ column }) {
      // 修改列
      this.$emit("checkColumnMethodExtends", { column });
      return true;
    },
    importMethodExtends({ file }) {
      const formBody = new FormData();
      formBody.append("file", file);
      return this.$XModal.message({
        message: `成功导入 测试 条记录！`,
        status: "success"
      });
    },
    contentMethodExtends({
      items,
      row,
      rowIndex,
      $rowIndex,
      column,
      columnIndex,
      $columnIndex,
      type,
      cell,
      $event
    }) {
      // console.log('都是干嘛滴:',
      //   items, row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, type, cell, $event
      // )
    },
    remoteExportMethod({ options }) {
      // console.log('数据导出测试:', options)
      const proxyInfo = this.$refs.xGrid.getProxyInfo();
      // 传给服务端的参数
      const body = {
        filename: options.filename,
        sheetName: options.sheetName,
        isHeader: options.isHeader,
        original: options.original,
        mode: options.mode,
        pager: proxyInfo.pager,
        ids:
          options.mode === "selected" ? options.data.map(item => item.id) : [],
        fields: options.columns.map(column => {
          return {
            field: column.property,
            title: column.title
          };
        })
      };
      // console('我要开始导出了')
      // return XEAjax.post('https://api.xuliangzhan.com:10443/api/pub/export', body).then(data => {
      //     if (data.id) {
      //         this.$XModal.message({ message: '导出成功，开始下载', status: 'success' })
      //         // 读取路径，请求文件流 => 开始下载
      //         location.href = `https://api.xuliangzhan.com:10443/api/pub/export/download/${data.id}`
      //     }
      // }).catch(() => {
      //     this.$XModal.message({ message: '导出失败！', status: 'error' })
      // })
    },
    guid: function() {
      // debugger;
      const id = new SnowflakeId();
      // console.log(id.generate())
      return id.generate();
    },
    footerSpanMethodExtends({ columns, data }) {
      // console.debug('footerSpanMethodExtends')
      this.$emit("footerMethodExtends", { columns, data });
    },
    footerMethodExtends({ columns, data }) {
      // console.debug('footerMethodExtends方法')
      this.$emit("footerMethodExtends", { columns, data });
    },
    spanMethodExtends({ columns, data }) {
      // console.debug('spanMethodExtends方法钩子')
      this.$emit("footerMethodExtends", { columns, data });
    },
    toolbarButtonClickEvent(event) {
      // console.log("尝试输出", event)
      if (event.button.hasOwnProperty("handler")) {
        event.button.handler(event);
      }
    },
    checkboxChange: function(val) {
      console.log("选中了----", val.records);
      this.$emit("checkboxRecords", val.records);
    },
    getSelected: function() {
      if(this.options.checkType=='radio')
        return this.$refs[this.xGrid].getRadioRecord()
      else if(this.options.checkType=='checkbox')
        return this.$refs[this.xGrid].getCheckboxRecords();
      else
        return this.$refs[this.xGrid].getCurrentRecord();
    },
    //修改可编辑单元格方法
    activeCellMethod: function({ column }) {
      // console.log(column,columnIndex,"sefrtry")
      if (column.editRender.props.isEdit == "N") {
        return false;
      } else {
        return true;
      }
      // return true;
    },
    validEvent() {
      let that = this;
      that.$refs[that.xGrid].$refs.xTable.validate(errMap => {
        console.log(errMap);
        if (errMap) {
          that.$XModal.message({
            status: "error",
            message: "校验不通过，有未填写项"
          });
        } else {
          that.$XModal.message({ status: "success", message: "校验成功！" });
        }
      });
    },
    dblclick(val) {
      this.$emit("dblclickrow", val.row);
    },
    getTableData(){
      return this.$refs[this.xGrid].getTableData();
    }
  }
};
</script>

<style lang="scss" scoped>
.tableTest {
  margin: 0.5px;
}
/*loading*/
$vxe-loading-background-color: rgba(0, 0, 0, 0.0);
$vxe-loading-z-index: 999; 
::v-deep .vxe-loading {background-color: rgba(0,0,0,.0) !important;}
</style>
